package com.yunc.modules.quartz.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.yunc.base.netty.WebSocketServerHandler;
import com.yunc.base.utils.R;
import com.yunc.modules.shop.entity.ShopRandomCode;
import com.yunc.modules.shop.service.IShopRandomCodeService;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * 测试集群部署
 * @author taocongcong
 * @create 2018-09-20 17:49
 */
@Component("scheduleTest")
@Slf4j
public class ScheduleTest {

    private static final Snowflake snowflake = IdUtil.createSnowflake(1, 1);

    @Autowired
    private IShopRandomCodeService shopRandomCodeService;

    public void test() {
        String orderNumber = snowflake.nextIdStr();
        ShopRandomCode shopRandomCode = new ShopRandomCode();
        shopRandomCode.setUserId("1");
        shopRandomCode.setCode(orderNumber);
        shopRandomCodeService.save(shopRandomCode);
        log.info("雪花算法创建的订单号，此刻的orderNum是 :{}，时间是：{}", orderNumber, DateUtil.formatDateTime(new Date()));
    }

    public void test1(){
        log.info("消息查看定时任务，测试所有客户的Channel");
        Map<String, ChannelGroup> userChannelMap = WebSocketServerHandler.userChannelMap;
        if (CollUtil.isNotEmpty(userChannelMap)) {
            // 遍历map
            for (Map.Entry<String, ChannelGroup> entry : userChannelMap.entrySet()) {
                ChannelGroup channelGroup = entry.getValue();
                // 遍历
                if (channelGroup != null && channelGroup.size() > 0) {
                    for (Channel channel : channelGroup) {
                        // 发送消息
                        String s = "你有消息待查看";
                        channel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(R.ok().put("type", "1").put("data", s))));
                    }
                }
            }
        }
    }

}
